from Home.models import *
from rest_framework.response import Response
from Home.ser.NavigationSer import *
from urllib.parse import urlencode
from Home.tools.AuthQuery import g

import time
class Login():
    def login(self):
        print("登录")
import requests
class DDLogin(Login):
    def login(self):
        from urllib.parse import quote
        params = [
            f"redirect_uri={quote('http://127.0.0.1:8000/home/nav/dingdingCallBack/')}",
            "response_type=code",
            "client_id=ding5vqytdbueu3cicyt",
            "scope=openid",
            "prompt=consent"
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return url
    def rollback(self,request):
        authCode = request.query_params.get('authCode')
        # 根据authCode获取用户accessToken
        data = {
            "clientId": "ding5vqytdbueu3cicyt",
            "clientSecret": "M8h_VRftMfxCv3Vi60FSpZQBY8s8IUI1QQBoHYc8N_D3lDWUXXn2BtGSWnuRRX04",
            "code": authCode,
            "grantType": "authorization_code"
        }
        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
        name = resp.get('nick')
        uid = resp.get('openId')
        phone = resp.get('mobile')

        # 登录，写入三方登录表和用户表
        sfl = SFModel.objects.filter(uid=uid, types=1).first()
        print(sfl)

        if not sfl:
            # 写入用户表
            # 手机号用户存在直接绑定,不存在注册新用户
            user = CusersModel.objects.filter(phone=phone).first()
            if not user:
                userinfo = {
                    "name": name,
                    "phone": phone,
                    # "password": phone,
                    # "username": phone
                }
                us = CuserSer(data=userinfo)
                if us.is_valid():
                    print("sabve")
                    user = us.save()
                else:
                    return Response({"code": 10001, "msg": (us.errors)})
            # 写入三方登录表
            sfinfo = {
                "types": 1,
                "token": accessToken,
                "uid": uid,
                "users": user.id
            }
            sfs = SFser(data=sfinfo)
            print(sfs.is_valid())
            if sfs.is_valid():
                sfs.save()
            else:
                return Response({"code": 10001, "msg": (sfs.errors)})
        else:
            print(sfl)
            user = sfl.users

            sfl.token = accessToken
            sfl.save()
        print("111111")
        # 生成jwt token并返回前端
        payload = {"userid": user.id, "username": user.name, "exp": int(time.time()) + 60 * 60 * 2}
        token = g.jwt_encode(payload)
        payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
        refreshToken = g.jwt_encode(payload)
        query = [f"userid={payload['userid']}", f"username={payload['username']}", f"token={token}",
                 f"refreshToken={refreshToken}"]
        # return HttpResponseRedirect(f'http://localhost:3000/ddtoken/?{"&".join(query)}')
        query_params = urlencode({
            'userid': str(user.id),
            'token': token
        })
        return  f'http://localhost:3000/ddtoken/?{query_params}'

class QQLogin(Login):
    def login(self):
        print("QQ登录")

class LoginFactory():
    def create_login(self):
        pass
    def rollback(self,request):
        pass


class DDLoginFactory(LoginFactory):
    def create_login(self):
        return DDLogin().login()
    def rollback(self,request):
        return DDLogin().rollback(request)

class QQLoginFactory(LoginFactory):
    def create_login(self):
        return QQLogin().login()



dd=DDLoginFactory()
